<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="班次:">
											<u--input v-model="baseFormData.ShiftName" placeholder="自动带出班次" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="开始投料日期:">
											<u--input v-model="baseFormData.StartTime" placeholder="开始投料日期" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="投料状态:" @click="ChangeResult()" required>
											<u--input v-model="baseFormData.ResultName" placeholder="自动带出投料状态" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
								</u-row>

								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="总重量:">
											<u--input v-model="baseFormData.TotalWeight" placeholder="自动带出总重量" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="加料人:">
											<u--input v-model="baseFormData.OperatorName" placeholder="自动带出加料人" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="备注:">
											<u--input v-model="baseFormData.FRemarks" placeholder="请输入备注"
												border="none"></u--input>
										</u-form-item>
									</u-col>
								</u-row>

							</u--form>

						</view>
						<view class="AddBottomBox">

							<view class="CancelBtn CancelBtnIcon">
								<u-icon class="icon" name="scan" color="#51d0d0" size="30" @click="ScanClick"></u-icon>
							</view>
							<button class="CancelBtn" @click="Addsubtable()">新增</button>
						</view>
						<view class="table">
							<table>
								<tr>
									<th width="8%">操作</th>
									<th width="8%">序号</th>
									<th>原材料</th>
									<th>原料批次</th>
									<th>标准重量</th>
									<th>重量</th>
								</tr>

								<tr v-for="(item, index) in tableData">
									<td class="sticky-col">
										<uni-icons type="trash" size="30" @click="trash(index)"></uni-icons>
									</td>
									<td>{{index + 1}}</td>
									<td @click="openBaseScreen('原材料', index)">
										<u--textarea v-model="item.MaterialName" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.MaterialBatch" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.StandardWeight" autoHeight border="none" disabled
											class="fixed-textarea"></u--textarea>
									</td>
									<td>
										<u--textarea v-model="item.Weight" autoHeight border="none" type='number'
											class="fixed-textarea"></u--textarea>
									</td>
								</tr>
							</table>
						</view>
					</view>
					<view class="DetailsbottomBtns">
						<button class="button1" block @click="submit">
							保&nbsp &nbsp 存
						</button>
					</view>
				</view>
			</template>

		</st-mc-framework>

		<u-toast ref="uToast"></u-toast>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm' :showCancelButton='true'
			@cancel='modalshow=false'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>

		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
		<u-action-sheet :actions="ResultList" :show="ResultShow" @select="ResultClick"
			@close="ResultShow=false"></u-action-sheet>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';
	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {

				ButtonShow: true,
				showMLoading: false,
				loadingName: '正在加载中……',

				baseFormData: {
					TotalWeight: null,
					FPlanQty: null,
					ProductName: '',
					ProductID: 0,
					ProductCode: '',
					ProductSpec: '',
					StartTime: '',
					BillNO: null,
					JobOrderID: null,
					WoOrderID: null,
					ProcedureName: '',
					TLStatus: null,
					ZS_AddPlasticID: null,
					EquipmentID: null,
					EquipmentName: '',
					OperatorName: '',
					EmplID: null,
					ShiftName: '',
					ShiftID: null,
					Result: 0,
					ResultName: '未投料',
					FRemarks: ''
				},

				tableData: [],
				tableDataIndex: null,
				modalshow: false,
				modaltitle: '',
				modalcontent: '',
				submitButton: '提交',
				submitButtonShow: true,
				MoludList: [],
				ProductNameselect: false, //第一次进来是否多个
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				ResultShow: false,
				ResultList: [{
						name: '已投料',
						id: 1,
						status: true
					},
					{
						name: '未投料',
						id: 0,
						status: false
					}
				], //重复测量筛选数组
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(onLoad) {
			var that = this
			uni.$on('refreshDetail', (res) => {
				that.getValue(res.data); // 调用目标方法
			});
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => that.showMLoading = state;
			// 主处理逻辑

			var detailsitem = JSON.parse(onLoad.Detailsitem)
			if (detailsitem.ZS_AddPlasticID) {
				setLoading(true);
				that.queryList(detailsitem.ZS_AddPlasticID);
				return;
			}
			// 统一处理表单默认值
			const formDefaults = {
				...detailsitem,
				EquipmentID: MesBasicInfo.warehouse.EquipmentID,
				EquipmentName: MesBasicInfo.warehouse.EquipmentName,
				StartTime: getFormatDate(new Date()),
				OperatorName: UserInfo.EmplName,
				EmplID: UserInfo.EmplID,
				ShiftName: MesBasicInfo.ShiftObj.ShiftName,
				ShiftID: MesBasicInfo.ShiftObj.ShiftID,
			};
			that.assignFormData(that.baseFormData, formDefaults);
			that.Request.request('getPGDBomde', {
				JobOrderID: detailsitem.JobOrderID
			}, function(res) {
				console.log(res);
				res.data.ds.map((item) => {
					item.Weight = item.Weight ? item.Weight : null
					item.ZS_AddPlasticDelID = item.ZS_AddPlasticDelID ? item.ZS_AddPlasticDelID : 0
					item.MaterialBatch = item.MaterialBatch ? item.MaterialBatch : ''
				})
				that.tableData = res.data.ds
			})
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {
			var that = this

		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {
			ChangeResult() {
				console.log('ssss');
				console.log('ssss');
				var that = this
				that.ResultShow = true
				console.log('ssss');
			},
			ResultClick(item) {
				console.log(item)
				var that = this
				// 统一处理表单默认值
				const formDefaults = {
					ResultName: item.name,
					Result: item.id,
				};
				that.assignFormData(that.baseFormData, formDefaults);
				that.ResultShow = false
			},
			Addsubtable() {
				var that = this;
				var obj = {
					MaterialID: null,
					MaterialCode: '',
					MaterialName: '',
					MaterialBatch: '',
					StandardWeight: null,
					Weight: null
				}
				that.tableData.push(obj)
			},
			ScanClick() {
				var that = this
				this.$scanPopup.openScan({
					success: function(res) {
						console.log(res);
						that.MoludChange(res.result, 'phone')
					},
					fail: function(fail) {
						console.log(fail);
					}
				})
			},
			gettableDatachild() {
				var tableDatachild = this.tableData[this.tableData.length - 1]
				return tableDatachild
			},
			// 处理扫码数据
			MoludChange(res, name) {
				let that = this;
				let parts = res.split("|");
				var Code = parts[1]
				var Batch = parts[2]
				const targetItems = this.tableData.filter(item => item.MaterialCode === Code);
				targetItems.forEach(item => {
					const formDefaults = {
						MaterialBatch: Batch
					};
					that.assignFormData(item, formDefaults); // 逐个更新
				});
			},

			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			getValue(payload) {
				var that = this;
				console.log(payload);
				that.showMLoading = false
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'人员': () => ({
						TestName: data.UserName,

					}),
					'产品': () => ({
						ProductName: data.ProductName,
						ProductID: data.ProductID
					}),
					'原材料': () => ({
						MaterialID: data.MaterialID,
						MaterialCode: data.MaterialCode,
						MaterialName: data.MaterialName,
						StandardWeight: data.StandardWeight
					}),
				};
				if (typeHandlers[type]) {
					if (type == '原材料') {
						Object.assign(that.tableData[that.tableDataIndex], typeHandlers[type]());
					} else {
						Object.assign(that.baseFormData, typeHandlers[type]());
						if (type == '产品') {
							that.Request.request('ZS_getMaterialList', {
								ProductID: that.baseFormData.ProductID,
								PageIndex: 1,
								PageSize: 30
							}, function(ret) {
								ret.data.ds.map((item) => {
									item.Remark = item.Remark ? item.Remark : '',
										item.TestStandardNUM = item.TestStandardNUM * 100 + '%'
								})
								Object.assign(that.tableData, that.tableData.concat(ret.data.ds));
							})
						}
					}
				}
				console.log(this.baseFormData);
				this.$forceUpdate()
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
				var parentData
				if (that.modaltitle == '提醒') {
					that.tableData.splice(that.tableDataIndex, 1)
				} else if (that.modaltitle == '提示') {
					var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
					parentData = initData[initData.length - 1]
					that.$refs.framework.ToLevel(parentData)
				}
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			openBaseScreen(str, index) {
				var that = this;
				var obj;
				// if (that.ButtonShow == true) {
				if (str == '人员') {
					obj = {
						cmd: 'getEmplByJobName',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'UserName', //查询结果显示的字段
						},
						param: {
							JobName: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '产品') {
					obj = {
						cmd: 'ZS_getProductList',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'ProductName', //搜索关键词，应包含在param中
							showText: 'ProductName', //查询结果显示的字段
						},
						param: {
							EquipmentID: that.baseFormData.EquipmentID,
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '原材料') {
					that.tableDataIndex = index
					obj = {
						cmd: 'getPGDBomde',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'MaterialName', //搜索关键词，应包含在param中
							showText: 'MaterialName', //查询结果显示的字段
						},
						param: {
							JobOrderID: that.baseFormData.JobOrderID,
							PageIndex: 1,
							PageSize: 30
						}
					}
				}

				console.log(obj);
				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
				// }

			},

			getTarget(arrayName, status) {
				const targetArray = this[arrayName];
				const obj = targetArray.find(item => item.id === status);
				return obj.name || '';
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getPGDMaterialDetail', {
						ZS_AddPlasticID: id
					}, function(ret) {
						that.showMLoading = false
						console.log(ret);
						that.ButtonShow = false
						const [firstItem] = ret.data.ds;
						const formDefaults = {
							...firstItem,
							StartTime: formatDateTime(firstItem.StartTime),
							// ResultName: firstItem.Result == 0 ? '未投料' : '已投料',
							ResultName: that.getTarget('ResultList', firstItem.Result)
						};
						that.assignFormData(that.baseFormData, formDefaults);
						that.tableData = ret.data.ds1
					})
				} catch (e) {
					that.showMLoading = false
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},

			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},

			submit() {
				var that = this
				var msg
				var show = true
				var parentData
				var initData = JSON.parse(JSON.stringify(this.$store.state.GuyueModule.ModuleData_select));
				var tableList = JSON.parse(JSON.stringify(this.tableData));


				// if (that.baseFormData.ProductName == '' || that.baseFormData.ProductName == null) {
				// 	msg = '请选择产品名称'
				// 	show = false
				// }
				tableList.some((item, index) => {
					if (item.Weight == '' || item.Weight == null) {
						item.Weight = '@'
					}
					if (item.MaterialBatch == '' || item.MaterialBatch == null) {
						msg = '请扫码带出原料批次';
						show = false;
					}
					return false; // 继续遍历下一个
				});
				if (show) {
					var mainObj = {
						FRemarks: that.baseFormData.FRemarks,
						OperatorName: that.baseFormData.OperatorName,
						EquipmentID: that.baseFormData.EquipmentID,
						ShiftID: that.baseFormData.ShiftID,
						Result: that.baseFormData.Result,
						StartTime: that.baseFormData.StartTime,
						ProductID: that.baseFormData.ProductID,
						JobOrderID: that.baseFormData.JobOrderID,
						ZS_AddPlasticID: that.baseFormData.ZS_AddPlasticID,
						WoOrderID: that.baseFormData.WoOrderID,
						MaterialCode: tableList.map(item => item.MaterialCode).join(','),
						ZS_AddPlasticDelID: tableList.map(item => item.ZS_AddPlasticDelID).join(','),
						MaterialID: tableList.map(item => item.MaterialID).join(','),
						StandardWeight: tableList.map(item => item.StandardWeight).join(','),
						MaterialName: tableList.map(item => item.MaterialName).join(','),
						Weight: tableList.map(item => item.Weight).join(','),
						MaterialBatch: tableList.map(item => item.MaterialBatch).join(','),
					}
					console.log(mainObj);
					that.Request.request('savePGDMaterial', mainObj, function(mainRes) {
						console.log(mainRes);
						if (mainRes.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							setTimeout(() => {
								that.queryList(mainRes.data.ds[0].ZS_AddPlasticID)
							}, 1000)
						} else {
							that.showModal('报错', mainRes.data.ds[0].msg);
						}
					})
				} else {
					that.showModal('报错', msg);
				}
			},
			// 子表删除
			trash(index) {
				var that = this
				that.tableDataIndex = index
				that.showModal('提醒', '是否删除第' + (index + 1) + '行');
			},


		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.DetailsbottomBtnsTow {
		button {
			margin: 0 5%;
			flex: 1;
		}
	}


	// 查询按钮
	.AddBottomBox {
		width: 100%;
		display: flex;
		align-items: center;
		padding: 2px 5px;
		justify-content: flex-end;
		box-sizing: border-box;

		.CancelBtnIcon {
			.icon {
				padding: 0;
				margin: 0;
			}
		}

		.CancelBtn {
			margin: 0 5px;
			align-items: center;
			text-align: center;
			display: flex;
			justify-content: center;
			background-color: #fff;
			color: #51d0d0;
			border: 1px solid #51d0d0;
			min-height: 40px;
			min-width: 70px;
			border-radius: 4px;
			font-size: 14px;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
			transition: all 0.3s ease;

			&:active {
				background-color: #e6f7f7;
				transform: translateY(1px);
			}
		}
	}
</style>